<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <title>列表排序</title>
</head>

<body>
    <div id="root">
        <!-- 遍历数组-人员列表 -->
        <input type="text" placeholder="请输入名字" v-model="keyword">
        <button @click="sorttype=2">年龄升序</button>
        <button @click="sorttype=1">年龄降序</button>
        <button @click="sorttype=0">原升序</button>
        <lu>
            <li v-for="(people,index) in filterpeople" :key="index">
                {{people.name}}-----{{people.age}}
            </li>
        </lu>
    </div>
    <script>
        new Vue({
            el: '#root',
            data: {
                keyword: '',
                sorttype: 0,
                peoples: [{
                    id: '001',
                    name: '马冬梅',
                    age: '20'
                }, {
                    id: '002',
                    name: '周冬雨',
                    age: '21'
                }, {
                    id: '003',
                    name: '周杰伦',
                    age: '22'
                }, {
                    id: '004',
                    name: '温兆伦',
                    age: '23'
                }],
                //  filterpeople: []

            },
            //监视属性实现
            // watch: {
            //     keyword: {
            //         immediate: true, // 当初始化时让  handler调用
            //         handler(value) {
            //             this.filterpeople = this.peoples.filter((p) => {
            //                 return p.name.indexOf(value) !== -1;
            //             });
            //         }
            //     }
            // }

            //计算属性实现
            computed: {
                filterpeople() {

                    const arr = this.peoples.filter((p) => {
                        return p.name.indexOf(this.keyword) !== -1;
                    })

                    if (this.sorttype) {
                        arr.sort((p1, p2) => {
                            return this.sorttype === 1 ? p2.age - p1.age : p1.age - p2.age;
                        })
                    }
                    return arr;

                }

            }
        })
    </script>
</body>

</html>